package com.tianya.interceptors;

import com.tianya.context.UserContext;
import com.tianya.domain.enums.Message;
import com.tianya.exception.CustomException;
import com.tianya.utils.JwtUtil;
import io.swagger.annotations.ApiModel;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author TianYaGuoKe
 * @date 2025/5/4 16:36
 * @description InterceptorHandle
 */
@ApiModel("拦截器处理类")
@Component
public class InterceptorHandle implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
            try {
                // 校验 token 并解析用户信息
                Long userId = jwtUtil.getUserIdFromToken(token);
                if (userId != null) {
                    // 将用户信息存储到上下文中（假设使用 ThreadLocal）
                    UserContext.setUserId(userId);
                    return true; // 继续执行后续逻辑
                }
            } catch (Exception e) {
                // token 校验失败，返回 401 未授权
                throw new CustomException(Message.AUTH_FAILED);
            }
        }
        throw new CustomException(Message.AUTH_FAILED);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后，视图渲染之前执行的逻辑
        System.out.println("InterceptorHandle - postHandle: " + request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求完成之后执行的逻辑，包括视图渲染完成
        System.out.println("InterceptorHandle - afterCompletion: " + request.getRequestURI());
        // 清理上下文中的用户信息
        UserContext.clearUserId();
    }
}